/**
 * 
 */
package org.cuatrovientos.erp;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

/**
 * @author Raquel
 *
 */
public class Customer {
	/**
	 * read
	 * returns the query of all the data of customer table
	 * @return result
	 */
    public String read(){
    	String result="";
    	try {
    		Class.forName("com.mysql.jdbc.Driver");
    		Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/erp","root","");
    		Statement stat = conn.createStatement();
    		ResultSet resultset = stat.executeQuery("select * from customer;");
    		  
    	    while (resultset.next()) {
    	     result =result +("id = " + resultset.getString("id"));
    	      result=result + ("name = " + resultset.getString("name"));
    	    }
    	} catch (Exception e) {
    		result="Error: " + e.getMessage();
   		}
    	
    	return result;
    }
    /**
     * create
     * insert into customer table a new customer with name and address
     * @param name
     * @param address
     * @return res
     */
    public String create(String name, String address){
    	String res="Done";
    	try{
    		Class.forName("com.mysql.jdbc.Driver");
    		Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/erp","root","");
    		Statement stat = conn.createStatement();
    		String insertQuery =  "insert into customer (name,address) values('"+name+"','"+address+"')";
  	  		int result = stat.executeUpdate(insertQuery);
    	}catch(Exception e){
  	  		res="Error: " + e.getMessage();
  	  	}
    	return res;
    }
    /**
     * update
     * Updates the data of customer with entered id
     * @param id
     * @param name
     * @param address
     */
    public String update(int id,String name, String address){
    	String res="Done";
    	try{
    		Class.forName("com.mysql.jdbc.Driver");
    		Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/erp","root","");
    		Statement stat = conn.createStatement();
   	  		String updateQuery = "update customer set address='"+address+"',name='"+name+"' where id='"+id+"'";
   	  		int result = stat.executeUpdate(updateQuery);
    	}catch(Exception e){
  	  		res="Error: " + e.getMessage();
  	  	}
    	return res;
    }
    /**
     * delete
     * deletes the customer with entered id
     * @param id
     */
    public String delete(int id){
    	String res="Done";
    	try{
    		Class.forName("com.mysql.jdbc.Driver");
    		Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/erp","root","");
    		Statement stat = conn.createStatement();
  	  		String deleteQuery = "delete from customer where id=" + id;
  	  		int result = stat.executeUpdate(deleteQuery);
    	}catch(Exception e){
  	  		res="Error: " + e.getMessage();
  	  	}
    	return res;	
    }

}
